package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.GroupTransAdpter;
import com.sam.im.heiqun.uis.adapters.NewFriendAdpter;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.EventBusType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 邀请添加好友
 */
public class GroupTransActivity extends BaseSwipeBackActivity implements NewFriendAdpter.NewFriendListClickListener {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.new_friends_list)
    RecyclerView newFriendsList;
    @BindView(R.id.activity_new_friends)
    LinearLayout activityNewFriends;
    private GroupTransAdpter mNewFriendAdpter;
    private PGService mPGservice;
    private String destType = "1";
    private String groupId;
    private String friendGroupId = "";
    private List<MessageEntivity> messageEntivities;


    @Override
    public int getContentViewId() {
        return R.layout.activity_new_friends;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.group_notifiction);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        UserEntivity userEntivity = ToolsUtils.getUser();

        mPGservice = PGService.getInstance();

        mNewFriendAdpter = new GroupTransAdpter(this);
        mNewFriendAdpter.setItemClickListener(this);
        newFriendsList.setLayoutManager(new LinearLayoutManager(this));
        newFriendsList.addItemDecoration(new DividerItemDecorationUtils(this, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        newFriendsList.setAdapter(mNewFriendAdpter);
        messageEntivities  = MessageEntivity.find(MessageEntivity.class, "fromid = ? and (type=? or type=?)"
                , new String[]{userEntivity.getId() + "", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "", Constant.MESSAGE_GROUP_ADD_APPLY + ""});

        if (null!=messageEntivities && messageEntivities.size() > 0){
            for (int i = 0; i < messageEntivities.size(); i++) {
                MessageEntivity msg = messageEntivities.get(i);
                msg.setMessageNum(0);
                msg.save();
            }
            EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
        }

        mNewFriendAdpter.refresh(messageEntivities);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      //  int id = (int) destid;
        notificationManager.cancel(0);//注销系统通知 系统通知id为0
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 接收到消息进行处理
    public void onAiteEvent(Integer string) {
        if (string == EventBusType.GROUP_TRANS_DELETE_GRPOUP){
            //刷新界面
            messageEntivities  = MessageEntivity.find(MessageEntivity.class, "fromid = ? and (type=? or type=?)"
                    , new String[]{ToolsUtils.getMyUserId() + "", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "", Constant.MESSAGE_GROUP_ADD_APPLY + ""});
//            messageEntivities  = MessageEntivity.find(MessageEntivity.class, "fromid = ? and type = ? "
//                    , new String[]{ToolsUtils.getMyUserId() + "", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + ""});

            mNewFriendAdpter.refresh(messageEntivities);
        }
    }

    @OnClick({R.id.pre_v_back, R.id.right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back: {
                scrollToFinishActivity();
                break;
            }
            case R.id.right://添加
            {
                startActivity(SeachFriendsActivity.class);
                break;
            }
        }
    }

    @Override
    public void onAgreeNewFriendClick(View view, final int position, int type) {
        if (0 == type) {
//            Bundle bundle = new Bundle();
////            bundle.putSerializable("friendInfo", mFriends.get(position));
//            bundle.putLong("id", messageEntivities.get(position).getDestid());
//            bundle.putInt("type", 2);
//            startActivity(FriendDetailActivity.class, bundle);
//            Bundle bundle = new Bundle();
//            bundle.putLong("groupid", messageEntivities.get(position).getDestid());
//            startActivity(ChatGroupMgrActivity.class, bundle);

            Log.i("ChatGroupMgrActivity", "onAgreeNewFriendClick: ========进入ChatGroupMgrActivity=========groupid="+messageEntivities.get(position).getDestid());
            JSONObject jsonObject = JSON.parseObject(messageEntivities.get(0).getContent());
            Long groupId = jsonObject.getLong("groupId");
            Intent intent = new Intent(GroupTransActivity.this, ChatGroupMgrActivity.class);
            intent.putExtra("groupid", groupId);
            startActivity(intent);

        }else if (1 == type) {//拒绝
            MessageEntivity messageEntivity = messageEntivities.get(position);
            if (null!=messageEntivity ){
                if (messageEntivity.getType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME){
                    deleteZhuanGroup(position);
                }else if (messageEntivity.getType() == Constant.MESSAGE_GROUP_ADD_APPLY){
                    updateGroupMember(position, "0");
                }
            }
        } else {//同意
            MessageEntivity messageEntivity = messageEntivities.get(position);
            if (null!=messageEntivity ){
                if (messageEntivity.getType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME){
                    agreeZhuanGroup(position);
                }else if (messageEntivity.getType() == Constant.MESSAGE_GROUP_ADD_APPLY){
                    updateGroupMember(position, "1");
                }
            }

        }
    }

    private void agreeZhuanGroup(final int position){
        showProgress(getResources().getString(R.string.commiting));

            /*{id=null, version=0, devType=null, geoId=0, msgId=3460c7d4-1595-4a34-b94a-84e5c369f498, fromid=2419, fromname=123025,
            fromType=3, destid=17244, content={"groupName":"罢罢罢","destId":17244,"groupId":2419},
            messageType=52, sendTime=1505442674346, receiveTime=0, status=0, userVoiceTime=0.0,
             userVoicePath={"groupName":"罢罢罢","destId":17244,"groupId":2419}, userVoiceUrl=null,
              fileUrl={"groupName":"罢罢罢","destId":17244,"groupId":2419}, filePath=null,
              imageIconUrl=http://123.57.47.19:8080/wmsMobile/upload/1503362239394_Wl31cR150336223643917244.png,
               uniqueness=null, type=0, sendState=0, content_fy=null, isShowFY=, isRead=false, isPayed=false, isklopen=false}*/

        Log.i("info", "onAgreeNewFriendClick: ======================groupid="+messageEntivities.get(position).getDestid());

        mPGservice.transGroupConfirm("" + messageEntivities.get(position).getDestid(), ToolsUtils.getMyUserId(), "1").subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.caozuo_fail));
                hideProgress();
            }

            @Override
            public void onNext(ValidateEntivity entivity) {

                ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, messageEntivities.get(position).getDestid());
                mImGroupEntivity.setCreaterId(Long.parseLong(ToolsUtils.getMyUserId()));
                mImGroupEntivity.save();

                JSONObject jhson = JSON.parseObject(messageEntivities.get(position).getContent());
                String destId = jhson.getString("destId");

                List<GroupFriendEntivity> groupFriendEntivitiesY = GroupFriendEntivity.find(GroupFriendEntivity.class, "uid = ? and belong_group_id=?",
                        new String[]{destId, messageEntivities.get(position).getDestid() + ""});
                if (null!=groupFriendEntivitiesY && groupFriendEntivitiesY.size() > 0){
                    GroupFriendEntivity mmm = groupFriendEntivitiesY.get(0);
                    mmm.setRole("3");
                    mmm.save();
                }
                List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "uid = ? and belong_group_id=?",
                        new String[]{ToolsUtils.getMyUserId(), messageEntivities.get(position).getDestid() + ""});
                if (null!=groupFriendEntivities && groupFriendEntivities.size() > 0){
                    GroupFriendEntivity mmm = groupFriendEntivities.get(0);
                    mmm.setRole("1");
                    mmm.save();
                }
                showToast(getResources().getString(R.string.caozuo_success));
                hideProgress();
                finish();
            }
        });
    }
    private void deleteZhuanGroup(final int position){
        //删除申请实体
        showProgress(getResources().getString(R.string.commiting));
        mPGservice.transGroupConfirm("" + messageEntivities.get(position).getDestid(), ToolsUtils.getMyUserId(), "2").subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {

                showToast(getResources().getString(R.string.caozuo_fail));
                hideProgress();
            }

            @Override
            public void onNext(ValidateEntivity entivity) {
                messageEntivities.get(position).delete();
//                    MessageEntivity.deleteAll(MessageEntivity.class, "type=? and fromid=?", new String[]{"" + messageEntivities.get(position).getType(), "" + messageEntivities.get(position).getFromid()});
                System.out.print("ss"+messageEntivities);
                Long messageid=messageEntivities.get(position).getId();
                SharedPreferences mysh=getSharedPreferences("TransferThePossessionOf",Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor=mysh.edit();
                editor.putLong(messageid+"messageid",2);
                //editor.putLong("messageid",messageid);
                editor.commit();
                mNewFriendAdpter.refresh(messageEntivities);

                showToast(getResources().getString(R.string.refuse_apply_success));
                scrollToFinishActivity();
                hideProgress();
            }
        });
    }

    /**
     * 审核群成员/更新群成员禁言状态 /chat/updateGroupMember
     * destId 群成员id number @mock=17228
     * groupId 群组id number @mock=2643
     * ope  number @mock=0
     * type  number @mock=1
     * userId  number @mock=17234
     */
    private void updateGroupMember(final int position, final String ope){
        //删除申请实体
        showProgress(getResources().getString(R.string.commiting));

        MessageEntivity messageEntivity = messageEntivities.get(position);
        String content = messageEntivity.getContent();
        if ((content.startsWith("\"") && content.endsWith("\"")) || (content.startsWith("'") && content.endsWith("'"))){
            content = content.substring(1,content.length() - 1);
        }
//        Log.i(TAG, "onBindViewHolder: ============messageEntivity.getContent()========"+content);

        JSONObject jhson = JSON.parseObject(content);
        String groupId = null!=jhson?jhson.getString("groupId"):"";
        Log.i("-----", "updateGroupMember: ==============destId=="+messageEntivities.get(position).getDestid()+"==groupId="+groupId+"==ope="+ope);
        if (null==groupId || TextUtils.isEmpty(groupId)){
            hideProgress();
            return;
        }
        mPGservice.updateGroupMember("" + messageEntivities.get(position).getDestid(), groupId, ope, "1", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.caozuo_fail));
                hideProgress();
            }

            @Override
            public void onNext(ValidateEntivity entivity) {
                messageEntivities.get(position).delete();
//                    MessageEntivity.deleteAll(MessageEntivity.class, "type=? and fromid=?", new String[]{"" + messageEntivities.get(position).getType(), "" + messageEntivities.get(position).getFromid()});
                if ("0".equals(ope)){//拒绝
                    Long messageid=messageEntivities.get(position).getId();
                    SharedPreferences mysh=getSharedPreferences("TransferThePossessionOf1",Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor=mysh.edit();
                    editor.putLong(messageid+"messageid",3);
                    //editor.putLong("messageid",messageid);
                    editor.commit();
                    mNewFriendAdpter.refresh(messageEntivities);

                    showToast("拒绝成功！");
                }else {
                    Long messageid=messageEntivities.get(position).getId();
                    SharedPreferences mysh=getSharedPreferences("TransferThePossessionOf1",Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor=mysh.edit();
                    editor.putLong(messageid+"messageid1",4);
                    //editor.putLong("messageid",messageid);
                    editor.commit();
                    mNewFriendAdpter.refresh(messageEntivities);
                    showToast("同意成功！");
                }
                scrollToFinishActivity();
                hideProgress();
            }
        });
    }


}
